package com.shockweb.rpc.spring;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.cglib.proxy.Enhancer;

import com.shockweb.common.log.LogManager;

import org.springframework.cglib.core.SpringNamingPolicy;

/**
 * 自定义的FactoryBean
 * 
 * @author 彭明华
 * 2018年1月26日 创建
 */
public class RemoteFactoryBean<T> implements InitializingBean, FactoryBean<T> {
	
	/**
	 * 注入innerClassName
	 */
	private String innerClassName;
	/**
	 * 注入innerClassName
	 * @param innerClassName
	 */
	public void setInnerClassName(String innerClassName) {
		this.innerClassName = innerClassName;
	}
	
	/**
	 * @see FactoryBean#getObject()
	 */
	@SuppressWarnings("unchecked")

	public T getObject() throws Exception {
		Class<?> innerClass = Class.forName(innerClassName);
		if (innerClass.isInterface()) {
			return (T) InterfaceProxy.newInstance(innerClass);
		} else {
			Enhancer enhancer = new Enhancer();
			enhancer.setSuperclass(innerClass);
			enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
			enhancer.setCallback(new MethodInterceptorImpl());
			return (T) enhancer.create();
		}
	}
	
	/**
	 * @see FactoryBean#getObjectType()
	 */

	public Class<?> getObjectType() {
		try {
			return Class.forName(innerClassName);
		} catch (ClassNotFoundException e) {
			LogManager.errorLog(this.getClass(),e);
		}
		return null;
	}
	
	/**
	 * @see FactoryBean#getObjectType()
	 */

	public boolean isSingleton() {
		return true;
	}
	/**
	 * @see InitializingBean#afterPropertiesSet()
	 */

	public void afterPropertiesSet() throws Exception {
	}
}
